package com.junmo.oauth.config.security;


import com.junmo.oauth.module.system.dao.SysUserRepository;
import com.junmo.oauth.module.system.entity.SysRole;
import com.junmo.oauth.module.system.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证管理器
 */
@Component
@AllArgsConstructor
@Slf4j
public class MyUserDetailService  implements UserDetailsService {
    private SysUserRepository sysUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名从数据库获取用户信息
        SysUser user = sysUserRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 得到用户角色
        Set<SysRole> roles = user.getRoles();
        Set<GrantedAuthority> authorities = new HashSet<>();
        //权限集合，先放角色，再放权限
        roles.forEach(role->{
            authorities.add( new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()) );
            role.getResources().forEach(resource->{
                authorities.add( new SimpleGrantedAuthority(resource.getResourceCode()) );
            });
        });
        return new SysUser( user.getUsername(),user.getPassword(),authorities);
    }
}
